package org.easylookandfeel.adapter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.UIManager.LookAndFeelInfo;

/**
 * A built-in implementation of {@link LookAndFeelAdapter} interface. It builds
 * a look and feel selection menu on a given {@link JMenu}. The client
 * application must only pass a reference to {@link JMenu} where look and feel
 * menu options will be placed in.
 * 
 * @author pcmnac@gmail.com
 * 
 */
public class MenuLookAndFeelAdapter extends AbstractLookAndFeelAdapter {

  /**
   * {@link JMenu} where look and feel menu options will be placed in.
   */
  private JMenu rootMenu;

  /**
   * Look and feel menu items.
   */
  private JMenuItem[] menuItems;

  /**
   * Look and feel button group.
   */
  private ButtonGroup lookAndFeelGroup;

  /**
   * Construtor.
   * 
   * @param rootMenu
   *          The menu where look and feel menu options will be placed.
   */
  public MenuLookAndFeelAdapter(JMenu rootMenu) {
    this.rootMenu = rootMenu;
  }

  /**
   * @see org.easylookandfeel.adapter.LookAndFeelAdapter#handleLookAndFeelChanged(int)
   */
  public void handleLookAndFeelChanged(int lookAndFeelIndex) {
    for (int i = 0; i < menuItems.length; i++) {
      if (lookAndFeelIndex == i) {
        menuItems[i].setSelected(true);
        break;
      }
    }
  }

  /**
   * @see org.easylookandfeel.adapter.LookAndFeelAdapter#initializeLookAndFeel(javax.swing.UIManager.LookAndFeelInfo[])
   */
  public void initializeLookAndFeel(LookAndFeelInfo[] looks) {
    menuItems = new JMenuItem[looks.length];
    lookAndFeelGroup = new ButtonGroup();
    for (int i = 0; i < looks.length; i++) {
      menuItems[i] = new JRadioButtonMenuItem(looks[i].getName());
      menuItems[i].addActionListener(new LookAndFeelActionListener(i));
      lookAndFeelGroup.add(menuItems[i]);
      rootMenu.add(menuItems[i]);
    }
  }

  /**
   * Handles look and feel menu actions.
   * 
   * @author pcmnac@gmail.com
   * 
   */
  class LookAndFeelActionListener implements ActionListener {
    int value;

    /**
     * Constructor
     * 
     * @param value
     *          The look and feel value (index).
     */
    public LookAndFeelActionListener(int value) {
      this.value = value;
    }

    /**
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    public void actionPerformed(ActionEvent e) {
      getManager().changeLookAndFeel(value);
    }

  }

}
